<?php 
	namespace Admin\Controller;
	class CateController extends CommonController{
		public function index()
		{
			$cateModel=D('category');
			$data['pid']=$_GET['id']?$_GET['id']:0;
			$ppid=$_GET['ppid']?$_GET['ppid']:0;
			//总条数
			$total=$cateModel->where($data)->count();
			//总页数
			$page=new \Think\Page($total,4);
			$page->setConfig('header','总页数');
			$page->setConfig('prev','上一页');
			$page->setConfig('next','下一页');
			//获取当前页
			$p=$page->nowPage;
			//echo $p;
			//exit;
			$page_str=$page->show();
			$limit=$page->firstRow.','.$page->listRows;
			$list=$cateModel->getAll($limit,$data);

			//var_dump($list);exit;
			$this->assign('page',$page_str);
			$this->assign('p',$p);
			$this->assign('ppid',$ppid);
			$this->assign('list',$list);
			$this->display();
		}

		public function add()
		{
			//接受当前页
			$p=$_GET['p'];
			if ($_GET['id']) 
			{
				$id=$_GET['id'];
				$sql="select `path` from `category` where id=$id";
				$model=M('category');
				$cate_path=$model->query($sql)[0]['path'].$id.',';
				$pid=$id;
			}else{
				$pid=0;
				$cate_path='0,';
			}
			$this->assign('p',$p);
			$this->assign('pid',$pid);
			$this->assign('cate_path',$cate_path);
			$this->display();
		}

		public function insert()
		{
			//接受当前页
			$p=$_GET['p'];
			$model=M('category');
			//根据表单提交的POST数据创建数据对象
			$data=$model->create();
			if (!$data) {
			// 如果创建失败表示验证没有通过 输出错误提示信息
				$this->error($model->getError());
			}else{
				$data['name']=$_POST['name'];
				$data['pid']=$_POST['pid'];
				$data['path']=$_POST['path'];
				$data['addtime']=time();

				//插入数据
				$res=$model->add($data);
				if ($res) 
				{
					$this->success('插入类名成功',U('Cate/index',['p'=>$p]),2);
					return false;
				}
			}
		}

		public function del()
		{
			$id=$_GET['id'];
			$model=M('category');
			$sql="select * from `category` where pid=$id";

			$res=$model->query($sql);

			if (!empty($res)) 
			{
				$this->error('不能直接删除类名！');
					return false;
			}else{
				$res1=$model->delete($id);
				$this->success('删除成功',U('Cate/index'),1);
				return false;
				}
		}

		public function change()
		{
			//接受当前页
			$p=$_GET['p'];
		//var_dump($p);exit;
			$where['id']=$_GET['id'];

			$model=M('category');
			$status=$model->where($where)->select();
			//var_dump($status);
			$data['status']=$status[0]['status']==0?1:0;
			//var_dump($data);
			$res=$model->where($where)->save($data);
			//var_dump($res);exit;
			if ($res) 
			{
				$this->redirect('Cate/index',['p'=>$p]);
			}
		}
	}
?>